import React, {useState,useEffect,} from 'react'

import CustomButton from "../CustomButton/CustomBotton"
import constants from "../../utils/constants"
import './FormCodeInput.css'
import {Toast} from "antd-mobile";

const FormCodeInput = (props) => {

    const {
        type,
        value,
        onChange,
        placeholder,
        codeBtnActive,
        setCodeBtnActive,
        codeSend,
    } = props

    const onCodeBtnClick = () => {
        setCounting(true)
        props.onCodeBtnClick()
    }

    const time = 60
    const [inputFocus, setInputFocus,] = useState(false)
    const [countdown, setCountdown,] = useState(time)
    const [counting, setCounting] = useState(false)
    const [recounted, setRecounted] = useState(false)

    const tick = () => {
        let id = setTimeout(() => {
            setCountdown(countdown - 1)
        }, 1000)
    }

    const recount = () => {
        setCounting(false)
        setRecounted(true)
        setTimeout(() => {
            setCountdown(time)
            setCodeBtnActive(true)
        }, 1000)
    }

    useEffect(() => {

        if (codeSend && codeBtnActive === false) {

            if ((countdown - 1) === 0) {
                recount()
            } else {
                if (counting) {
                    tick()
                }
            }
        }
    })

    const codeBtnTemplate = (
        <div className='custom-input-code-btn'>
            <CustomButton
                size='xs'
                color={codeBtnActive ? '#fff': '#bbb'}
                bg={codeBtnActive ? `#FFA500` : '#E8E8E8'}
                onClick={codeBtnActive ? onCodeBtnClick : null}
                shadow={codeBtnActive? '0px 2px 4px 0px rgba(250,114,104,0.4)' : ''}
            >
                {codeSend && countdown > 0? `重新发送(${countdown})s` : '获取验证码'}
            </CustomButton>
        </div>
    )

    const template = (
        <div className={inputFocus? 'custom-input custom-input-touched' : 'custom-input'}>
            <input
                type={type}
                placeholder={placeholder}
                value={value}
                onChange={onChange}
                onFocus={e => setInputFocus(true)}
                onBlur={e => setInputFocus(false)}
            />
            {codeBtnTemplate}
        </div>
    )

    return template
}

export default FormCodeInput
